<template>
  <view class="register-container">
    <image class="logo" src="/static/lanqiao-logo.svg"></image>
    <input v-model="phone" type="number" placeholder="请输入手机号" class="input" />
    <input v-model="name" type="text" placeholder="请输入昵称" class="input" />
    <input v-model="password" type="password" placeholder="请输入密码" class="input" />
    <input v-model="confirmPassword" type="password" placeholder="请确认密码" class="input" />
    <button class="register-btn" @click="register">注册</button>
    <view class="login-link" @click="toLogin">已有账号？立即登录</view>
  </view>
</template>


<script>
import config from "@/config.js";

export default {
  data() {
    return {
      phone: '',
      name: '',
      password: '',
      confirmPassword: '',
      defaultAvatar: '/static/头像.png' // 默认头像路径
    };
  },
  methods: {
    validatePhone() {
      return /^1\d{10}$/.test(this.phone);
    },
    validatePassword() {
      return this.password.length >= 6;
    },
    validateName() {
      return this.name.trim().length > 0;
    },
    toLogin() {
      uni.navigateTo({ url: '/pages/login/login' });
    },
    async register() {
      if (!this.phone) {
        return uni.showToast({ title: '请输入手机号', icon: 'none' });
      }
      if (!this.validatePhone()) {
        return uni.showToast({ title: '请输入正确的11位手机号', icon: 'none' });
      }
      if (!this.name) {
        return uni.showToast({ title: '请输入昵称', icon: 'none' });
      }
      if (!this.validateName()) {
        return uni.showToast({ title: '昵称不能为空', icon: 'none' });
      }
      if (!this.password) {
        return uni.showToast({ title: '请输入密码', icon: 'none' });
      }
      if (!this.validatePassword()) {
        return uni.showToast({ title: '密码长度至少6位', icon: 'none' });
      }
      if (this.password !== this.confirmPassword) {
        return uni.showToast({ title: '两次输入密码不一致', icon: 'none' });
      }

      // 检查用户是否已存在
      try {
        const checkResponse = await new Promise((resolve, reject) => {
          uni.request({
            url: `${config.api_host}/users?username=${this.phone}`,
            method: 'GET',
            success: (res) => {
              resolve(res);
            },
            fail: (err) => {
              reject(err);
            }
          });
        });
        if (checkResponse.data.length > 0) {
          return uni.showToast({ title: '该手机号已注册', icon: 'none' });
        }
      } catch (error) {
        console.error('检查用户是否存在失败:', error);
        return uni.showToast({ title: '检查用户是否存在失败，请重试', icon: 'none' });
      }

      // 注册新用户
      const newUser = {
        username: this.phone,
        name: this.name,
        password: this.password,
        avatar: this.defaultAvatar,
        createdAt: new Date().toISOString()
      };

      try {
        const registerResponse = await new Promise((resolve, reject) => {
          uni.request({
            url: `${config.api_host}users`,
            method: 'POST',
            data: newUser,
            header: {
              'Content-Type': 'application/json'
            },
            success: (res) => {
              resolve(res);
            },
            fail: (err) => {
              reject(err);
            }
          });
        });
        uni.showToast({ title: '注册成功', icon:'success' });
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login/login' });
        }, 1500);
      } catch (error) {
        console.error('注册失败:', error);
        uni.showToast({ title: '注册失败，请重试', icon: 'none' });
      }
    }
  }
};
</script>


<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.logo {
  width: 120px;
  height: 120px;
  margin-bottom: 30px;
}

.input {
  width: 300px;
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0 10px;
  margin-bottom: 20px;
}

.register-btn {
  width: 300px;
  height: 45px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
}

.login-link {
  color: #999;
  margin-top: 15px;
  cursor: pointer;
}
</style>